package com.xydtech.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 字符串加解密（可逆）
 *
 * @author yuzhiguo
 * @date 2024/10/23 下午5:19
 */
public class AESEncryptionUtils {
    protected static final Logger logger = LoggerFactory.getLogger(AESEncryptionUtils.class);
    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;

    /**
     * 加密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        SecretKey secretKey = generateKey(key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密
     * @param encryptedData
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedData, String key) throws Exception {
        SecretKey secretKey = generateKey(key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    private static SecretKey generateKey(String key) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes(StandardCharsets.UTF_8));
        keyGenerator.init(KEY_SIZE, random);
        return new SecretKeySpec(keyGenerator.generateKey().getEncoded(), ALGORITHM);
    }

    public static void main(String[] args) {
        try {
            String key = "";
            String data = "Hello World!";

            String encryptedData = encrypt(data, key);
            System.out.println("加密 Data: " + encryptedData);

            String decryptedData = decrypt(encryptedData, key);
            System.out.println("解密 Data: " + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}